var NAME_SEPARATOR = " ";
var ADDRESS_SEPARATOR = '_$_';
var Coupon_NotReachQuota = "0500007";
var Coupon_NotValid = "401";
var useDiscountCode = '';


//获取Object
function g(nodeId) {
    return document.getElementById(nodeId);
}


//初始化订单页面
function call(url, param, errorMsg) {
    jQuery.ajax({
        type:"POST",
        dataType:"json",
        url:url,
        data:param,
        success:function (data) {

            if (data != null) {
                if (data.errorMessage != 'undefined' && data.errorMessage != null && data.errorMessage != '') {
                    alert(data.errorMessage);
                }
                /**
                 * login、cookie拦截器返回错误
                 */
                if (data.error != 'undefined' && data.error != null && data.error != "") {
                    if (data.error == "NoCart") {
                        goCart();
                        return;
                    }
                    if (data.error == 'NotLogin') {
                        alert("Your session has expired. Please login again.");
                        window.location.href = PurchaseAppConfig.OrderLoginUrl;
                        return;
                    }
                }


                if (data.error == 'undefined' || data.error == null || data.error == '') {

                    var o = new myorder();
                    o.order = data;
                    if (data.balance != 'undefined' && data.balance != null) {
                        o.balance = data.balance;
                    }
                    if (data.areaName != 'undefined' && data.areaName != null) {
                        o.areaName = data.areaName;
                    }
                    var result = TrimPath.processDOMTemplate("order_jst", o);
                    g("show").innerHTML = result;


                    if (data.areaName == "0") {

                        Edit_Consignee();//如果不存在收货人信息 默认打开编辑功能
                    }
                    //                    processCart();
                    var cartResult = TrimPath.processDOMTemplate("skuList_jst", data);
                    g("part_cart").innerHTML = cartResult;
                    g("itemsNum").innerHTML = data.cart.itemsNum;
                    var cw = getCurrencyWord();
                    g("subtotalLable").innerHTML = cw + data.cart.totalPromotionPrice.amount;
                    g("totalLable").innerHTML = cw + data.cart.totalPromotionPrice.amount;
                    var couponData = TrimPath.processDOMTemplate("showCoupon", o);
                    //是否显示优惠券码
                    if (!isEmpty(data.eptCoupon)) {   //有优惠券时
                        g("couponDiv").innerHTML = couponData;
                        //防止重复扣优惠券
                        if (!isEmpty(data.eptCoupon.code)) {
                            useDiscountCode = data.eptCoupon.code;
                        }
                        //重新加载计算价格
                        showDiscount(data.eptCoupon.discount);
                    } else {  //无优惠券时
//                        g('couponDiv').innerHTML = g('blankCoupon').innerHTML
                        $('#useDiscountCodeText').val('');
                    }
                    if (data.areaName != "0") {
                        calculateFreight(data.shortName);
                    }

                }
            }
        },
        complete:function (XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 400 ||
                XMLHttpRequest.status == 408 ||
                XMLHttpRequest.status == 500 ||
                XMLHttpRequest.status == 501 ||
                XMLHttpRequest.status == 502 ||
                XMLHttpRequest.status == 503 ||
                XMLHttpRequest.status == 504 ||
                XMLHttpRequest.status == 505 ||
                XMLHttpRequest.status == 506 ||
                XMLHttpRequest.status == 507 ||
                XMLHttpRequest.status == 508) {
                window.location.href = errorUrl + Math.random();
            }
        }
    });
}

/**
 * 选择某种运输方式
 * 1.保存当前运输方式以及其对应的运费
 * 2.重新计算页面上展现的订单金额和运费金额
 * @param shipType    运输方式
 * @param shipFee    运费
 */
function showPrice(shipType, shipFee, rmbFee, rate) {
    var ship = mReplace(g("shipLable").innerHTML);
    var discount = mReplace(g("discountLable").innerHTML);
    var subtotal = mReplace(g("subtotalLable").innerHTML);

    //异步请求保存 当前选择的运输方式，运费价格
    //var data = "shipType=" + shipType + "&totalFee=" + rmbFee + "&rate=" + rate;
    /*jQuery.ajax({
        type:"POST",
        dataType:"html",
        url:PurchaseAppConfig.OrderDomain + "/saveShipAndFreight.action?rt=" + Math.random(),
        data:data,
        success:function (data) {
        }
    });*/
    //var cw = getCurrencyWord();
    //重新计算运费和订单总价 重新展现
    g("shipLable").innerHTML = '￥ ' + formatFloat(shipFee, 2) + '元';
    g("totalLable").innerHTML = '￥ ' + formatFloat((p(subtotal) - p(discount) + p(shipFee)), 2) + '元';
}

/**
 * 根据币种Cookie翻译对应的符号
 * @return
 */
function getCurrencyWord() {

    var cw = getCookie('currency');
    var ret = '';
    switch (cw) {
        case  'USD':
            ret = '$';
            break;
        case  'HKD':
            ret = '$';
            break;
        case  'AUD':
            ret = '$';
            break;
        case  'GBP':
            ret = '£';
            break;
        case  'EUR':
            ret = '€';
            break;
        default :
            ret = '￥';
            break;
    }

    return  "CNY" + ret + " ";
}

/**
 * 读取Cookie
 * @param objName
 * @return
 */
function getCookie(objName) {//获取指定名称的cookie的值
    var arrStr = document.cookie.split(";");
    for (var i = 0; i < arrStr.length; i++) {
        var temp = arrStr[i].split("=");
        if (temp[0] == objName) return unescape(temp[1]);
    }
}

/**
 * 显示优惠价格及计算最终价格
 * @param discount
 */

function showDiscount(discount) {
    if (discount == null) {
        discount = "0.00";
    }
    var ship = mReplace(g("shipLable").innerHTML);
    var subtotal = mReplace(g("subtotalLable").innerHTML);
    var cw = getCurrencyWord();
    var dd = formatFloat(discount, 2);
//	dd = dd == 0 ? "0.00" : dd;
    g("discountLable").innerHTML = cw + dd;
    g("totalLable").innerHTML = cw + formatFloat((p(subtotal) - p(discount) + p(ship) ), 2);
}
/**
 * 计算商品总价
 * @param totalPrice
 */
function showTotalPrice(totalPrice) {
    var cw = getCurrencyWord();
    g("totalLable").innerHTML = cw + formatFloat(totalPrice);
}

function p(str) {
    return parseFloat(str);
}

function formatFloat(src, pos) {
    var disc = Math.round(src * Math.pow(10, pos)) / Math.pow(10, pos);
    if (disc < 0) {
        disc = 0;
    }
    return disc.toFixed(2);
}

function mReplace(value) {
    var cw = getCurrencyWord();
    value = value.replace("￥", ""); //处理有可能出事默认的情况 所以默认先替换一下$
    value = value.replace(cw, "");
    value = value.replace("元", "");
    value = value.replace(" ", "");
    return  value.replace(/,/g, "");
}

String.prototype.trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, "");
}
/**
 * 运费计算
 * @param country
 */
function calculateFreight(country) {
    clearWaitInfo();
    var data = "eptCountry=" + country;
    showWaitInfo('正在保存您的收件人信息。请稍候。。。', g('saveConsigneeInfo'));
    jQuery.ajax({
        type:"POST",
        dataType:"json",
        url:PurchaseAppConfig.OrderDomain + "/getFreight.action?rt=" + Math.random(),
        data:data,
        success:function (data) {
            if (data == null) {
                return;
            }
            var result = TrimPath.processDOMTemplate("shipTextArea", data);
            g("shipTextAreaHide").style.display = "";
            g("shipTextAreaHide").innerHTML = result;
        }

    });
}


/*****************************************编辑收货人信息***************************************/
/*****************************************************************************************/
var OldConsignee = "";
//编辑收货人信息
function Edit_Consignee(obj) {
    clearWaitInfo();
    //OldConsignee = g("part_consignee").innerHTML;
    showWaitInfo('您的请求正在提交。请稍候。。。', obj);
    $("#part_consignee").removeClass("showconsignee").addClass("hideconsignee");
    $("#edit_consignee").removeClass("hideconsignee").addClass("showconsignee");
    g('Consignee_Hidden_Type').value = 0;
	
    /*jQuery.ajax({
        type:"POST",
        dataType:"json",
        url:PurchaseAppConfig.OrderDomain + "/getAreaInfo.action?rt=" + Math.random(),
        data:"",
        success:function (data) {
            if (data != null) {

                *//**
                 * 拦截器错误返回
                 *//*
                if (data.error != 'undefined' && data.error != null && data.error != "") {
                    if (data.error == "NoCart") {
                        goCart();
                        return;
                    }
                    if (data.error == 'NotLogin') {
                        window.location.href = PurchaseAppConfig.OrderLoginUrl;
                    }
                }

                if (data.flag == true && data.consigneeInfo != 'undefined' && data.consigneeInfo != null) {

                    var result = TrimPath.processDOMTemplate("edit_consignee", data);
                    //设置省市县地址

                    g("part_consignee").innerHTML = result;

                    g('Consignee_Hidden_Type').value = 1;//设置隐藏编辑状态为打开
                    if (data.consigneeInfo.phone != 'undefined' && data.consigneeInfo.phone != null) {
                        var phoneStr = data.consigneeInfo.phone.split("-");
                        if (phoneStr.length >= 2) {
                            var countryCode = phoneStr[0];
                            if (countryCode == '+00867643-') {
                                countryCode = '';
                            }
                            var phoneNum = data.consigneeInfo.phone.replace(countryCode + '-', '');
                            g('consignee_countryCode').innerHTML = countryCode + '-';
                            g('consignee_phone').value = phoneNum;
                        }
                    }
                    //设置省市县地址
                    if (data.consigneeInfo.area != 'undefined' && data.consigneeInfo.area != null) {

                        //选中的省
                        if (data.provincesHtml != 'undefined' && data.provincesHtml != null && data.provincesHtml != "") {
                            g('div_Country').innerHTML = data.provincesHtml;
                            $("#consignee_country>option").each(function (i) {
                                if (data.consigneeInfo.area.provinceId == this.value) {
                                    this.selected = true;
                                    return false;
                                }
                            });
                        }

                        //选中的市
                        if (data.citysHtml != 'undefined' && data.citysHtml != null && data.citysHtml != "") {
                            g('div_State').innerHTML = data.citysHtml;
                            $("#consignee_state>option").each(function (i) {
                                if (data.consigneeInfo.area.cityId == this.value) {
                                    this.selected = true;
                                    return false;
                                }
                            });
                        }

                    }
                    else {
                        if (data.errorMessage != 'undefined' && data.errorMessage != null && data.errorMessage != "") {
                            alert(data.errorMessage);
                        }
                    }
                } else {
                    if (data.errorMessage != 'undefined' && data.errorMessage != null && data.errorMessage != "") {
                        alert(data.errorMessage);
                    }
                }
            }
        }
    });*/
}

//清除默认值
function clearTemp(obj) {
	var defaultValue="请输入收货人姓名";
    if (obj.value == defaultValue) {
        obj.value = '';
        obj.setAttribute("class", "cinp cinp1");
    }
}



/**
 * 更改国家
 */
function changeCountry(obj, defaultCitys, defaultCountys, defaultTown) {
    var cid = obj.value;
    if (cid == -22) {
        return;
    }
    
    var countryCode = obj.options[obj.selectedIndex].attributes['countrycode'].nodeValue;

    g('div_State').innerHTML = "<select class='cinp cinp3'  onchange='changeState(this)' id='consignee_state'><option value='-22'>请选择</option></selected>";
    //更新电话区域的国家码显示
    g('consignee_countryCode').innerHTML = countryCode + '-';
    $('#consignee_phone').val('');

    jQuery.ajax({
        type:"POST",
        dataType:"json",
        url:"/RemoteSensing/district/getProvince.action?cid=" + cid,
        data:"",
        success:function (data) {
            if (data != null) {
                if (data.ERROR != null && data.ERROR != "") {
                    if (data.ERROR == "ERROR_NULL_CART") {
                        goCart();
                        return;
                    }
                    if(data.ERROR = "ERROR_NULL_USER"){
                    	window.location.href = '/RemoteSensing/jsp/user.jsp';
                    }
                }
            }

            if (data != null && data.option != "") {
                g('div_State').innerHTML = data.option;
                changeState(document.getElementById("consignee_state"), 0, 0);
            } else {
                g('div_State').innerHTML = "<select ><option value='-22'>请选择</option></selected>";
            }
        }
    });
}


/**
 * 更改市
 * @param obj
 * @param defaultCountys
 * @param defaultTown
 */
function changeState(obj, defaultCountys, defaultTown) {

    removeAlert('state_check');
    var cid = obj.value;
    if (cid == -1) {
        g('div_State').innerHTML = "<select class='cinp cinp3'  onchange='changeState(this)'  id='consignee_state'><option value='-1' selected='selected'>Other</option></selected> <input  type='text'  class='cinp cinp2' onfocus='removeAlert(\"state_check\")' onblur='check_state()'  id='consignee_country_extend'/>";
        showAlert('Required field', g('consignee_state').parentNode, 'state_check');
    }
}


/*****************************************保存收货人信息***************************************/
/*****************************************************************************************/




function savePart_consignee(obj) {
    clearWaitInfo();
    if (check_all()) {
        var provinceid = g('consignee_state').value;   //stateId

        var name = getByName('consignee_name').value;   //收货人: firstName lastName
        

        //地址= Address1_$_Address2_$_city_$_state_$_Country
        var address = g('consignee_address').value;
        var city = g('consignee_city').value;
        var province = "";

        if (provinceid > 0) {
            province = g('consignee_state').options[g('consignee_state').selectedIndex].attributes['statename'].nodeValue;
        } else if (provinceid == -1) {
        	province = g('consignee_country_extend').value;
        }

        var country = g('consignee_country').options[g('consignee_country').selectedIndex].attributes['countryName'].nodeValue;

        var ocAddress = getAddress(address, city, province, country);


//        var ocEmail = g('consignee_email').value;
        var postCode = g('consignee_postcode').value;

        var countryCode = g('consignee_country').options[g('consignee_country').selectedIndex].attributes['countryCode'].nodeValue;
        var phone = countryCode + '-' + g('consignee_phone').value;   //电话
        
        var email = g('consignee_email').value;

        var data = {"name": name, "address": address, "city": city, "province": province, "country": country, 
        		"phone": phone, "postCode": postCode, "email": email};
        showWaitInfo('正在保存您的收件人信息。请稍候。。。', g('saveConsigneeInfo'));
        jQuery.ajax({
            type:"POST",
            dataType:"json",
            url:'/RemoteSensing/order/saveConsignee.action?r=' + Math.random(),
            data: JSON.stringify(data),
            contentType:"application/json",
            success:function (data) {
                if (data != null) {
                    if (data.ERROE != null && data.ERROR != "") {
                        if (data.ERROR == "ERROR_NULL_USER") {
                            window.location.href = '/RemoteSensing/jsp/user.jsp';
                        }
                    }
                }
                if (data.ERROR == "SUCCESS") {//正确保存
                	$("#part_consignee").removeClass("hideconsignee").addClass("showconsignee");
                	$("#edit_consignee").removeClass("showconsignee").addClass("hideconsignee");
                    
                    window.location.reload();
                    
                    g('Consignee_Hidden_Type').value = 1;

                    //显示可选用的运输方式
                    //calculateFreight(shortName);

                } else {
                    if (data.message != null && data.message != "") {
                        alert(data.message);
                    }
                    clearWaitInfo();
                    return;

                }
            }

        });

    }
}


var OldPayType = "";


function goCart() {
    window.location.href = '/RemoteSensing/cart/getCart.action?r=' + Math.random();
}

function clearWaitInfo() {
    var newd = g("waitInfo");
    if (newd != null) {
        newd.parentNode.removeChild(newd);
    }
}

//显示等待信息
function showWaitInfo(info, obj) {
    try {
        if (obj == null)return;
        var newd = document.createElement("span");
        newd.className = 'tips9';
        newd.id = 'waitInfo';
        newd.innerHTML = info;
        obj.parentNode.appendChild(newd);
    } catch (e) {
    }
}

//显示EPT 优惠券 等待信息
function showCouponWaitInfo(info, obj) {
    try {
        if (obj == null)return;
        var newd = document.createElement("span");
        newd.className = 'tips5';
        newd.id = 'waitInfo';
        newd.innerHTML = info;
        obj.parentNode.appendChild(newd);
    } catch (e) {
    }
}

function showCouponAlert(info, obj) {
    try {
        if (obj == null)return;
        var newd = document.createElement("span");
        newd.className = 'tips5';
        newd.id = 'couponAlert';
        newd.innerHTML = info;
        obj.parentNode.appendChild(newd);
    } catch (e) {
    }
}

function showCouponSuccess(info, obj) {
    try {
        if (obj == null)return;
        var newd = document.createElement("span");
        newd.className = 'tips55';
        newd.id = 'couponSuccess';
        newd.innerHTML = info;
        obj.parentNode.appendChild(newd);
    } catch (e) {
    }
}

//显示等待信息
function showSubmitWaitInfo(info, obj) {
    try {
        if (obj == null)return;
        var newd = document.createElement("span");
        newd.className = 'tips10';
        newd.id = 'waitInfo';
        newd.innerHTML = info;
        obj.parentNode.appendChild(newd);
    } catch (e) {
    }
}

function showSubmitAlert(info, obj) {
    try {
        if (obj == null)return;
        var newd = document.createElement("span");
        newd.className = 'tips6';
        newd.id = 'submitAlert';
        newd.innerHTML = info;
        obj.parentNode.appendChild(newd);
    } catch (e) {
    }
}

function clearSubmitAlert() {
    var newd = g("submitAlert");
    if (newd != null) {
        newd.parentNode.removeChild(newd);
    }
}
/**
 * 购物车拆单显示处理
 */
function processCart() {
    jQuery.ajax({
        type:"POST",
        dataType:"json",
        url:PurchaseAppConfig.OrderDomain + "/skuList.action?rt=" + Math.random(),
        data:"",
        success:function (result) {
            if (result != null) {
                if (result.error != null && result.error != "") {
                    if (result.error == "NoCart") {
                        goCart();
                        return;
                    }
                }
            }
            if (result != null && result.cart != null) {
                // ---------商品清单的信息------
                var data = TrimPath.processDOMTemplate("skuList_jst", result);
                document.getElementById("part_cart").innerHTML = data;
            }
        }
    });

}

//对收货人地址可选项的处理
function getAddress(address, city, province, country) {

	return  country + ADDRESS_SEPARATOR + province + ADDRESS_SEPARATOR + city + ADDRESS_SEPARATOR + address ;


}
function isEmpty(obj) {
    if (obj == 'undefined' && obj == null && obj == '') {
        return true;
    }
    return false;

}

//正则
function trimTxt(txt) {
    return txt.replace(/(^\s*)|(\s*$)/g, "");
}

//检查是否为空
function InputIsEmpty(inputId) {
    if (trimTxt(g(inputId).value) == '') {
        return true;
    }
    return false;
}

function isChina(){
	if(g('consignee_country').value == '3'){
	//if(g('consignee_country').value == '100000004'){
    	return true;
    }
	return false;
}

//地址允许通过的字符 26个英文字母，10个数字，英文逗号，英文句号
function addr_accept(temp_str) {

    temp_str = trimTxt(temp_str);
    temp_str = temp_str.replace(/＃/g, "/");
    temp_str = temp_str.replace(/－/g, "/");
    temp_str = temp_str.replace(/＿/g, "/");
    temp_str = temp_str.replace(/＇/g, "/");
    temp_str = temp_str.replace(/＋/g, "/");
    temp_str = temp_str.replace(/：/g, "/");
    temp_str = temp_str.replace(/．/g, "/");
    temp_str = temp_str.replace(/，/g, "/");
    temp_str = temp_str.replace(/／/g, "/");
    temp_str = temp_str.replace(/＼/g, "/");
    temp_str = temp_str.replace(/　/g, "/");

    temp_str = temp_str.replace(/#/g, "/");
    temp_str = temp_str.replace(/-/g, "/");
    temp_str = temp_str.replace(/\\/g, "/");
    temp_str = temp_str.replace(/:/g, "/");
    temp_str = temp_str.replace(/\'/g, "/");
    

    if(isChina()){
    	return true;
    }else{
    	var regExp = /^[ ,.0-9a-zA-Z-+_/]+$/;
        return regExp.test(temp_str);
    }
    

}

function is_forbid(temp_str) {
    temp_str = trimTxt(temp_str);
    temp_str = temp_str.replace('*', "@");
    temp_str = temp_str.replace('--', "@");
    temp_str = temp_str.replace('+', "@");
    temp_str = temp_str.replace('\'', "@");
    temp_str = temp_str.replace('\\', "@");
    temp_str = temp_str.replace('$', "@");
    temp_str = temp_str.replace('^', "@");
    temp_str = temp_str.replace('#', "@");
    temp_str = temp_str.replace(';', "@");
    temp_str = temp_str.replace('<', "@");
    temp_str = temp_str.replace('>', "@");
    temp_str = temp_str.replace('"', "@");
    temp_str = temp_str.replace('=', "@");
    temp_str = temp_str.replace('{', "@");
    temp_str = temp_str.replace('}', "@");
    var forbid_str = new String('@,%,~,&');
    var forbid_array = new Array();
    forbid_array = forbid_str.split(',');
    for (i = 0; i < forbid_array.length; i++) {
        if (temp_str.search(new RegExp(forbid_array[i])) != -1)
            return false;
    }
    return true;
}

function getByName(inputName) {
    var names = document.getElementsByName(inputName);
    if (names.length < 1) {
        return;
    } else {
        return names[0];
    }
}

//用于判断用户名为空
function checkEmptyByName(inputName, defaultValue) {
    if ((trimTxt(getByName(inputName).value) == '') || (trimTxt(getByName(inputName).value) == defaultValue)) {
        getByName(inputName).value = defaultValue;
        getByName(inputName).setAttribute("class", "cinp cinp1 f-grey");
        return true;
    }
    return false;
}


//--------------------校验------------------------


//检查firstName
function check_firstName() {
    removeAlert('firstName_empty');
    removeAlert('firstName_forbid');
    var pNode = getByName('consignee_name').parentNode;
    if (checkEmptyByName('consignee_name', "请输入收货人姓名")) {
        showAlert('收货人不能为空！', pNode, 'firstName_empty');
        return false;
    }
    //防止跨站漏洞，过滤特殊字符
    if (!is_forbid(getByName('consignee_name').value)) {
        showAlert('名字中不能包含特殊字符！ ', pNode, 'firstName_forbid');
        return false;
    }
    getByName('consignee_name').setAttribute("class", "cinp cinp1");
    return true;
}



function check_name() {
    removeAlert('name_success');
    var pNode = getByName('consignee_name').parentNode;
    if (check_firstName()) {
        showSuccess(pNode, 'name_success');
        return true;
    } else {
        return false;
    }
}

//检查Address
function check_address() {
    removeAlert('address_success');
    removeAlert('address_empty');
    removeAlert('address_invalid');
    var pNode = g('consignee_address').parentNode;
    if (InputIsEmpty('consignee_address')) {
        showAlert('收货地址不能为空！', pNode, 'address_empty');
        return false;
    }
    
    if(isChina()){
    	if(g('consignee_address').value.length > 80){
    		
    		showAlert('收回地址不能多于80个字符！', pNode, 'address_empty');
            return false;
    	}
    }
    
    if (!addr_accept(g('consignee_address').value)) {
        showAlert('收货地址不能包含特殊字符！', pNode, 'address_invalid');
        return false;
    }
    showSuccess(pNode, 'address_success');
    return true;
}


//检查city
function check_city() {
    removeAlert('city_success');
    removeAlert('city_empty');
    removeAlert('city_invalid');

    var pNode = g('consignee_city').parentNode;
    if (InputIsEmpty('consignee_city')) {
        showAlert('必填字段！', pNode, 'city_empty');
        return false;
    }

    if (!addr_accept(g('consignee_city').value)) {
        showAlert('不能包含特殊字符！', pNode, 'city_invalid');
        return false;
    }

    showSuccess(pNode, 'city_success');
    return true;
}


//state

function check_state() {
    removeAlert('state_success');
    removeAlert('state_check');
    removeAlert('stateExt_check');
    removeAlert('stateExt_invalid');
    if (g('consignee_state').value == '-22') {
        showAlert('必填字段！', g('consignee_state').parentNode, 'state_check');
        return false;
    }
    //当stateid为-1时，判断手写的空格是否为空
    if (g('consignee_state').value == '-1') {
        if (InputIsEmpty('consignee_country_extend')) {
            showAlert('必填字段', g('consignee_state').parentNode, 'stateExt_check');
            return false;
        }
        if (!addr_accept(g('consignee_country_extend').value)) {
            showAlert('不能含有特殊字符！', g('consignee_state').parentNode, 'stateExt_invalid');
            return false;
        }

    }

    showSuccess(g('consignee_state').parentNode, 'state_success');
    return true;
}

function check_country() {

    removeAlert('country_success');
    removeAlert('country_check');
    if (g('consignee_country').value == '-22') {
        showAlert('Required field', g('consignee_country').parentNode, 'country_check');
        return false;
    }
    showSuccess(g('consignee_country').parentNode, 'country_success');
    return true;
}


//检查邮政编码    符合规则的是26个字母10个数字 英文逗号, 英文。加号+ 减号-
function check_postcode() {
    removeAlert('postcode_success');
    removeAlert('postcode_empty');
    removeAlert('postcode_invalid')
    var pNode = g('consignee_postcode').parentNode;
    var postNum = $.trim($("#consignee_postcode").val());
    if (InputIsEmpty('consignee_postcode')) {
        showAlert('必填字段', pNode, 'postcode_empty');
        return false;
    }

    if (postNum.length > 20) {
        showAlert('邮政编码不能大于20个字符', pNode, 'postcode_invalid');
        return false;
    }

    postNum = postNum.replace(/#/g, "/");
    postNum = postNum.replace(/-/g, "/");
    postNum = postNum.replace(/\\/g, "/");
    postNum = postNum.replace(/:/g, "/");
    postNum = postNum.replace(/\'/g, "/");
    var regExp = /^[ ,.0-9a-zA-Z-_/]+$/;
    if (!regExp.test(postNum)) {
        showAlert('Invalid field format. Special characters are not allowed', pNode, 'postcode_invalid');
        return false;
    }


    showSuccess(pNode, 'postcode_success');
    return true;
}

//检查电话    符合规则的是26个字母10个数字 英文逗号 英文。加号+ 减号-
function check_phone() {
    removeAlert('phone_success');
    removeAlert('phone_empty');
    removeAlert('phone_invalid');
    var pNode = g('consignee_phone').parentNode;

    if (InputIsEmpty('consignee_phone')) {
        showAlert('必填字段', pNode, 'phone_empty');
        return false;
    }
//    if (!is_forbid(g('consignee_phone').value)) {
//        showAlert('Phone number format is invalid ', pNode, 'phone_forbid');
//        return false;
//    }
    var phoneNum = $.trim($("#consignee_phone").val());
    
    var regExp = /^0?(13[0-9]|15[012356789]|18[0236789]|14[57])[0-9]{8}$/;
    if (!regExp.test(phoneNum)) {
        showAlert('联系人电话格式不正确！', pNode, 'phone_invalid');
        return false;
    }
    var countryCode = g('consignee_country').options[g('consignee_country').selectedIndex].attributes['countryCode'].nodeValue;
    var phoneNum = countryCode + '-' + g('consignee_phone').value;
    if (phoneNum.length > 15) {
        showAlert('联系人电话不能多于15个！', pNode, 'phone_invalid');
        return false;
    }
    showSuccess(pNode, 'phone_success');
    return true;
}

//email
function check_email() {
    removeAlert('email_success');
    removeAlert('email_empty');
    removeAlert('email_ff');
    var pNode = g('consignee_email').parentNode;
    if (InputIsEmpty('consignee_email')) {
        showAlert('必填字段', pNode, 'email_empty');
        return false;
    }
    if (g('consignee_email').value != '') {
        var pNode = g('consignee_email').parentNode;
        var myReg = /(^\s*)\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*(\s*$)/;
        if (!myReg.test(g('consignee_email').value)) {
            showAlert('Email格式错误！', pNode, 'email_ff');
            return false;
        }
    }
    showSuccess(pNode, 'email_success');
    return true;
}


//校验收货人信息
function check_all() {
    if (check_name() && check_address() && check_city() && check_state()
        && check_country() && check_postcode() && check_phone() && check_email()
        ) {
        return true;
    } else {
        return false;
    }

}

function check_coupon() {
    if (InputIsEmpty('useDiscountCodeText')) {
        showCouponAlert("Please enter your coupon code", g('useDiscountCodeText'));
        return false;
    }
    return true;
}

//删除提示信息
function removeAlert(infoSign) {
    if (g(infoSign) == null) {
        return;
    }
    g(infoSign).parentNode.removeChild(g(infoSign));
}


//显示提示信息
function showAlert(info, obj, infoSign) {
    if (g(infoSign) != null) {
        return;
    }
    var newd = document.createElement("span");
    newd.id = infoSign;
    newd.className = 'tips3';
    newd.innerHTML = info;
    obj.appendChild(newd);
}

function showClearBtn(obj, infoSign) {
    if (g(infoSign) != null) {
        return;
    }
    var newd = document.createElement("b");
    newd.id = infoSign;
    newd.onclick = "clearCouponEPT()";
    obj.appendChild(newd);
}

function clearClearBtn(infoSign) {
    if (g(infoSign) == null) {
        return;
    }
    g(infoSign).parentNode.removeChild(g(infoSign));
}

function showSuccess(obj, infoSign) {
    var newd = document.createElement("span");
    newd.id = infoSign;
    newd.className = 'tips4';
    obj.appendChild(newd);
}

//添加EPT优惠券
function add_Coupon_ept(value) {
    removeAlert('couponAlert');
    removeAlert('couponSuccess');
    if (!check_coupon()) {
        return;
    }
    var useDiscountCodeText = g('useDiscountCodeText').value;

    if (useDiscountCode != '' && useDiscountCode == useDiscountCodeText) {
        return;
    }
    useDiscountCode = useDiscountCodeText;
    var code = value;
    var data = "code=" + code;
    var pNode = getByName('add_coupon_button').parentNode;
    //  showCouponWaitInfo('Validating your coupon. Please wait.', pNode);
    jQuery.ajax({
        type:"POST",
        dataType:"json",
        url:PurchaseAppConfig.OrderDomain + "/addCouponEpt.action?rt=" + Math.random(),
        data:data,
        success:function (data) {
            if (data == null) {
                //  clearWaitInfo();
                showCouponAlert("There was a problem adding your coupon.", g('useDiscountCodeText'));
                showDiscount(data.discount);
                return;
            }
            if (data.error == 'NotLogin') {
                window.location.href = PurchaseAppConfig.OrderLoginUrl;
            }
            if (data.flag) {//正确保存
                // clearWaitInfo();
//                alert("The coupon code is valid and we have applied your discount!");
                showCouponSuccess("The coupon code is valid and we have applied your discount.", g('useDiscountCodeText'));
                //是否显示优惠券码 清除按钮
                $('#useDiscountCodeText').parent().append('<b onclick="clearCouponEPT(this)">X</b>');
                //更新价格显示
                showDiscount(data.discount);

            } else {
                //   clearWaitInfo();

                if (data.ResultCode == Coupon_NotReachQuota) {
                    showCouponAlert("Minimum order amount not reached.", g('useDiscountCodeText'));
                } else if (data.ResultCode == Coupon_NotValid) {
                    showCouponAlert("Sorry, the coupon code you entered is invalid. Please try again.", g('useDiscountCodeText'));
                } else {
                    showCouponAlert("There was a problem adding your coupon.", g('useDiscountCodeText'));
                }
                showDiscount(data.discount);
                return;

            }
        }

    });
}

//清除优惠券
function clearCouponEPT(obj) {
    removeAlert('couponAlert');
    removeAlert('couponSuccess');
    var couponCode = getByName('coupon_code');
    var data = "code=" + couponCode;
    var pNode = getByName('add_coupon_button').parentNode;
    // showCouponWaitInfo('Clearing your coupon. Please wait.', pNode);
    jQuery.ajax({
        type:"POST",
        dataType:"json",
        url:PurchaseAppConfig.OrderDomain + "/clearCouponEpt.action?rt=" + Math.random(),
        data:data,
        success:function (data) {
            if (data == null) {
                //   clearWaitInfo();
                showCouponAlert("There was a problem clearing your coupon.", g('useDiscountCodeText'));
                ;
                return;
            }
            if (data.error == 'NotLogin') {
                window.location.href = PurchaseAppConfig.OrderLoginUrl;
            }
            if (data.flag) {//正确清除
                //    clearWaitInfo();
                showCouponSuccess("You have successfully cleared your coupon.", g('useDiscountCodeText'));
                $('#useDiscountCodeText').val('');
                $(obj).remove();
                useDiscountCode = ''; //清空页面缓存                
                //显示空白页面
//                g('couponDiv').innerHTML = g('blankCoupon').innerHTML;
                //清除优惠券价格
                showDiscount(0.00);

            } else {
                showCouponAlert("There was a problem clearing your coupon.", g('useDiscountCodeText'));
            }
        }

    });

}

function submitOrder() {


    if (check_submit_isClose()) {
        //showSubmitWaitInfo('We are currently processing your order, please wait.', g('submitWaitInfo'));
        var payType = "";

        var payTypeRadio = document.getElementsByName('payType');

        for (i = 0; i < payTypeRadio.length; i++) {
            if (payTypeRadio[i].checked) {
                payType = payTypeRadio[i].value;
            }
        }
        
        var shipType = "";

        var shipTypeRadio = document.getElementsByName('shippingType');

        for (i = 0; i < shipTypeRadio.length; i++) {
            if (shipTypeRadio[i].checked) {
            	shipType = shipTypeRadio[i].value;
            }
        }

        jQuery.ajax({
            type:"POST",
            dataType:"json",
            url: '/RemoteSensing/order/saveOrder.action?payType=' + payType + '&shipType=' + shipType,
            success:function (result) {
                if (result != null) {
                    if (result.ERROR != null && result.ERROR != "") {
                        if (result.ERROR == "NO_CART") {
                            goCart();
                            return;
                        }
                    }
                }
                alert(result.ERROR)
                /*if(result.sor != null && !result.sor.flag && result.sor.resultCode=='checkStock_exception'){
                	
                	alert("Sorry! We currently have not enough units available. Please either amend your quantity or email us at contact@jd.com and we can inform you when stock is available.");
                	window.location.href = "http://cart.en.jd.com/cart/cart.html";
                }else if(result.sor != null && !result.sor.flag && result.sor.resultCode=='phone_error'){
                	
                	clearWaitInfo();
                    alert("There was a problem to submit your order. Please modify your Phone Number.");
                }else */
                if (result.ERROR != null && result.ERROR == "SUCCESS") {
                    window.location.href = "/RemoteSensing/order/getSuccessOrder.action?orderid=" + result.ORDER_ID;
                    //window.location.href = result.sor.payUrl;
                } else {
                    clearWaitInfo();
                    alert("提交订单时发生未知错误！");
                }
            }

        });
    }
}

function check_submit_isClose() {
    clearSubmitAlert();
    var errInfo = "";
    var consigenn = g('Consignee_Hidden_Type').value;
    //校验支付是否选择
    //校验配送信息
    //检查是否都关闭
    if (consigenn == 0) {
        errInfo = "请先保存收货地址！";
        showSubmitAlert(errInfo, g("submitWaitInfo"));
        return false;
    }

    if (!checkShip()) {
        errInfo = "请选择配送方式！";
        showSubmitAlert(errInfo, g("submitWaitInfo"));
        return false;
    }

    if (!checkPayment()) {
        errInfo = "请选择付款方式！";
        showSubmitAlert(errInfo, g("submitWaitInfo"));
        return false;
    }

    return true;


}

function checkShip() {
    var ships = document.getElementsByName('shippingType');

    for (i = 0; i < ships.length; i++) {
        if (ships[i].checked) {
            return true;

        }
    }
    return false;

}


function checkPayment() {

    var payTypeRadio = document.getElementsByName('payType');

    for (i = 0; i < payTypeRadio.length; i++) {
        if (payTypeRadio[i].checked) {
            return true;

        }
    }
    return false;
}

//---------------------------礼品卡------------------------
function myorder() {
    this.order = null;
    this.balance = null;
    this.areaName = '0';

}


//call(PurchaseAppConfig.OrderDomain + "/getNewOrderInfo.action?rt=" + Math.random());
